package com.citywithincity.db;

import java.sql.Connection;
import java.sql.SQLException;

import com.citywithincity.db.impl.ArImpl;
import com.citywithincity.db.interfaces.Ar;
import com.citywithincity.db.interfaces.EAr;
import com.citywithincity.db.interfaces.IDataSourceProvider;

public class ArFactoryImpl implements ArFactory {

	private IDataSourceProvider dataSource;
	private ArImpl ar;
	private EArImpl<?> eAr;
	private Connection connection;
	private ConnectionDescription description;
	

	public ArFactoryImpl(
			ConnectionDescription description,
			IDataSourceProvider dataSource
			) {
		this.dataSource = dataSource;
		this.description = description;

	}
	
	private Connection getConnection() {
		if (connection == null) {
			try {
				connection = dataSource.getConnection();
			} catch (SQLException e) {
				throw new DBException(e);
			}
		}
		return connection;
	}
	
	@Override
	protected void finalize() throws Throwable {
		dataSource = null;
		description = null;
	}
	

	@SuppressWarnings({ "unchecked" })
	public <T> EAr<T> createEAr(Entity<T> info) {
		if (eAr == null) {
			eAr = new EArImpl<T>(description.getSqlDriver(),getConnection());
		}else {
			eAr.setConnection(getConnection());
		}
		
		eAr.setInfo(info);
		return (EAr<T>) eAr;
	}

	public Ar createAr() {
		if (ar == null) {
			ar = new ArImpl(description.getSqlDriver(),getConnection());
		}else {
			ar.setConnection(getConnection());
		}
		
		return ar;
	}

	

	public void releaseConnection() {
		if(ar!=null){
			ar.releaseConnection();
			ar = null;
		}
		if(eAr!=null){
			eAr.releaseConnection();
			eAr=null;
		}
		if(connection!=null){
			dataSource.close(connection);
			connection = null;
		}
	}


	
}
